package com.weixin.paleituo.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import com.weixin.paleituo.R;

/**
 * <describe>
 *
 * @author fengzhen
 * @version version, 2018/4/15
 */

@SuppressLint("AppCompatCustomView")
public class CleanEditText extends EditText {
    public CleanEditText(Context context) {
        super(context);
        initClean();
    }

    public CleanEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initClean();
    }

    public CleanEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initClean();
    }

    private void initClean() {
        setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getContext(), R.mipmap.del), null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            Drawable drawable = ContextCompat.getDrawable(getContext(), R.mipmap.del);
            // 计算图片点击可响应的范围，计算方法见
            int drawHeight = drawable.getIntrinsicHeight();
            int drawWidth = drawable.getIntrinsicWidth();
            Rect imageBounds = new Rect(
                    this.getWidth() - drawWidth - drawWidth,
                    0,
                    this.getWidth(),
                    this.getHeight());
            if (imageBounds.contains((int) event.getX(), (int) event.getY())) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }
}
